package com.github.freegeese.site.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Arrays;
import java.util.HashSet;

/**
 * 自定义安全领域数据，继承AuthorizingRealm后既能够从该安全领域对象获取认证信息，也可以获取授权信息
 */
public class CustomRealm extends AuthorizingRealm {
    /**
     * 获取认证信息
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = String.valueOf(upToken.getPassword());

        if ("admin".equals(username) && password.equals("123456")) {
            SysUser user = new SysUser();
            user.setUsername(username);
            user.setPassword(password);
            return new SimpleAuthenticationInfo(user, password, getName());
        }
        throw new AccountException("帐号或密码不正确！");
    }

    /**
     * 获取授权信息
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        System.out.println(user.getUsername());
        SimpleAuthorizationInfo authzInfo = new SimpleAuthorizationInfo();
        authzInfo.setRoles(new HashSet<>(Arrays.asList("admin", "test")));
        authzInfo.setStringPermissions(new HashSet<>(Arrays.asList("add", "update")));
        return authzInfo;
    }
}
